package com.webproject.shop.service.impl;

import com.webproject.shop.common.BusinessException;
import com.webproject.shop.common.ErrorCode;
import com.webproject.shop.dao.ProductMapper;
import com.webproject.shop.service.CartService;
import com.webproject.shop.pojo.Cart;
import com.webproject.shop.dao.CartMapper;
import com.webproject.shop.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Iterator;
import java.util.List;

@Service
public class CartServiceImpl implements CartService, ErrorCode {

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ProductService productService;

    @Override
    public List<Cart> selectCartByUserName(String username)
    {
        List<Cart> carts = cartMapper.selectByUsername(username);
        return carts;
    }


    //购物车删除
    @Override
    public void deleteCart(Cart cart){
        cartMapper.deleteCart(cart);
    }

    //购物车新增
    @Override
    public void updateCart(Cart cart){
        cartMapper.updateCart(cart);
    }

    //购物车修改
    @Override
    public void insertCart(Cart cart){
        Cart cart2 = cartMapper.selectCartByCart(cart);
        if (cart2 == null)
        {
            cartMapper.insert(cart);
        }
        else{
            cart.setProNum(cart.getProNum()+cart2.getProNum());
            cartMapper.updateCart(cart);
        }
    }

    //购物车结算,需要构成事务
    @Override
    @Transactional
    public void createOrder(String username){
        List<Cart> carts = cartMapper.selectByUsername(username);
        //遍历购物车
        for(Cart cart : carts){
            //判断商品是否充足
            if(cart.getProNum()>productMapper.selectByPrimaryKey(cart.getProId()).getProAmount()) {
                throw new BusinessException(STOCK_NOT_ENOUGH, "有商品库存不足！");
            }
            //判断商品是否存在
            else if(productMapper.selectByPrimaryKey(cart.getProId())==null) {
                throw new BusinessException(PARAMETER_ERROR, "有商品不存在！");
            }
            //可继续执行操作
            else {
                boolean successful = productService.decreaseAmount(cart.getProId(),cart.getProNum());
                if (!successful) {
                    throw new BusinessException(STOCK_NOT_ENOUGH, "库存不足！");
                }
                cartMapper.deleteCart(cart);
            }
        }
    }



}
